﻿using System;
using System.IO;
using System.Web.Mvc;
using System.Web.Routing;

namespace QG.FrontDesk.com.Attbutes
{
    /// <summary>
    /// 异常过滤器
    /// </summary>
    public class MyExceptionAttribute : HandleErrorAttribute
    {
        public override void OnException(ExceptionContext filterContext)
        {
            //调用父类的捕获异常
            base.OnException(filterContext);
            //报错信息
            string exception = filterContext.Exception.ToString();
            //报错位置控制器名
            string controllername = filterContext.RouteData.Values["Controller"].ToString();
            //报错位置方法名
            string actionname = filterContext.RouteData.Values["Action"].ToString();
            //拼接字符串
            string msg = $"时间:{DateTime.Now},在控制器:{controllername},方法名:{actionname},出现了异常：{exception}";
            //写入路径，应配置Web.config
            string path = @"C:\\log.txt";
            //写入文件
            File.AppendAllText(path, msg);

             path = filterContext.HttpContext.Request.Path;
            //创建一个路由
            var route = new RouteValueDictionary { { "Controller", "Home" }, { "Action", "Error" }, { "ReturnUrl", path } };
            //跳转到指定路由
            filterContext.Result = new RedirectToRouteResult(route);
        }
    }
}